<template>

    <UxDialog :visible="show" title="" @close="close()" class="login-dialog-warp dialog-responsive">
        <div class="login-dialog">
            <!-- 注册、登录 -->
            <div v-if="status == 1 || status == 2" :class="[
                    { 'diabody-reg': status == 1 },
                    { 'diabody-login': status == 2 },
                ]">
                <h2 v-text="
                        (status == 1 && 'Sign up to PODpartner') ||
                        (status == 2 && 'Sign in to PODpartner')
                    "></h2>
                <button @click="loginOther" class="google-btn">
                    <img src="@/assets/images/google.svg" class="svg-google">
                    <p v-text="
                            (status == 1 && 'Sign up with Google') ||
                            (status == 2 && 'Sign in with Google')
                        "></p>
                </button>
                <span class="division">Or</span>
                <LoginForm :type="actionName" :data.sync="actionData" :tipData.sync="actionTip" @submit="actionFuc" @checkData="checkData"></LoginForm>
                <p class="other-link" v-if="status == 1">
                    By clicking Sign up you agree to PODpartner's
                    <a href="/document/terms-service" target="_blank">terms of service</a>
                    and
                    <a href="/document/privacy-policy" target="_blank">privacy policy</a>
                </p>
                <p class="other-link" v-else>
                    <a @click="toStatus(3)">Forgot password?</a>
                </p>
                <button v-if="status == 1" type="text" @click="toStatus(2)">
                    Sign in
                </button>
                <button v-else type="text" @click="toStatus(1)">
                    <p>Sign up</p>
                </button>
            </div>
            <!-- 忘记密码 -->
            <div v-if="status == 3" class="diabody-forget">
                <h2>Password reset</h2>
                <h4 v-text="
                        (fStatus == 1 &&
                            'Please enter your registered email, and we will send you a password reset link.') ||
                        (fStatus == 2 &&
                            'We just sent an email to ' +
                                forgetEmail +
                                ' with password reset instructions. Please check it.')
                    "></h4>
                <form class="login_form" v-if="fStatus == 1">
                    <label>
                        <input :maxlength="64" placeholder="Email" v-model="forgetEmail" onkeyup="this.value=this.value.replace(/(\s*)/g,'')" :class="forgetShow == 1 && 'error-border'" />
                        <em v-if="forgetShow == 1">
                            Please enter a valid mailbox
                        </em>
                        <em v-if="forgetShow == 2">
                            This email address is already in use.
                            <a @click="toStatus(1)">Sing up</a>
                        </em>
                    </label>
                </form>
                <p v-if="fStatus == 2" class="other-link">
                    Did not receive the mail?
                    <a @click="toFstatus(1)">Resend</a>
                </p>
                <button type="primary" @click="doForgetPass" :class="fStatus == 2 && 'visibility-hid'">
                    <p>Send</p>
                </button>
                <p>
                    <span>Return to </span><a @click="toStatus(2)">Sign in</a>
                </p>
            </div>
        </div>
    </UxDialog>
    <!-- <button @click="close()" class="login-close iconfont icon-guanbi"></button> -->
    <!-- <div class="login" :class="{ active: show }"> -->
    <!-- </div> -->
</template>

<script>
import Md5 from "js-md5";
import RE from "@/utils/RE";
import { mapGetters } from "vuex";

export default {
    name: "LoginDialog",
    props: {
        force: { type: Boolean, default: false }, // 是否强制登录
    },
    computed: {
        ...mapGetters({ isLogin: "getIsLogin" }),




        ...mapGetters('user', {
            userInfo: "getUserInfo",
        }),
        actionName () {
            return this.status == 1 ? "reg" : "login";
        },
        actionData () {
            return this.status == 1 ? this.regData : this.loginData;
        },
        actionTip () {
            return this.status == 1 ? this.regTip : this.loginTip;
        },
        actionFuc () {
            return this.status == 1 ? this.doReg : this.doLogin;
        },
    },
    data () {
        return {
            show: false,
            loading: false,
            callBackArray: [], //回调函数数组
            status: 1,
            fStatus: 1,
            regTip: {
                fullname: "",
                email: "",
                psw: "",
            },
            loginTip: {
                email: "",
                psw: "",
            },
            regData: {
                fullname: "",
                email: "",
                psw: "",
                allow: true,
            },
            loginData: {
                email: "",
                psw: "",
                allow: true,
            },
            forgetEmail: "",
            forgetShow: "",
        };
    },
    watch: {
        isLogin: {
            handler: function (newval, oldval) {
                if (oldval != newval) {
                    if (newval) {
                        // 登录了
                        this.loginCallBack(); //执行回调
                        this.$emit("loginSuccess"); //登录成功
                        //重置回调
                        this.close();
                        this.initData();
                    } else {
                        // 未登录
                        this.checkForceLogin();
                    }
                }
            },
            deep: true,
            immediate: true,
        },
        // show: {
        //     handler: function (v, ov) {
        //         var mo = function (e) {
        //             e.preventDefault();
        //         };
        //         if (!process.client) {
        //         } else if (v) {
        //             //禁止滚动
        //             document.body.style.overflow = "hidden";
        //             document.body.style.width = "100vw";
        //             document.addEventListener("touchmove", mo, false); //禁止页面滑动
        //         } else {
        //             /***取消滑动限制***/
        //             document.body.style.overflow = ""; //出现滚动条
        //             document.body.style.width = "";
        //             document.removeEventListener("touchmove", mo, false);
        //         }
        //     },
        //     immediate: true,
        // },
    },
    methods: {
        //谷歌授权登录
        async loginOther (n) {
            let opener = window.open("about:blank", "_blank", "width=550,height=800");
            let res = await this.$http("getGoogleLogin");
            if (res.code == 0) {
                opener && (opener.location = res.data);
            } else {
                opener && opener.close();
            }
        },
        //登录
        async doLogin () {
            let data = this.loginData;

            if (this.loading) {
                return;
            }

            this.checkData("login", data);
            if (this.loginData.allow) {
                let email = (this.loginData.email || "").replace(
                    /(^\s*)|(\s*$)/g,
                    ""
                );
                let password = (this.loginData.psw || "").replace(
                    /(^\s*)|(\s*$)/g,
                    ""
                );
                let resdata = {
                    email: email,
                    password: Md5(password),
                    password_verify: Md5(password),
                };

                this.loading = true;
                let res = await this.$http("postUserLogin", resdata);
                if (res.code == 0) {
                    this.$store.dispatch("setToken", res.data);
                    this.$uxMessage.success("Login successful");
                    this.loading = false;
                    return;
                }
                if (res.code == 2) {
                    this.$set(this.loginTip, "email", res.msg);
                }
                if (res.code == 6006) {
                    this.$set(this.loginTip, "psw", "Incorrect password");
                }
                this.loading = false;
                this.$uxMessage.warning(res.msg);
            }
        },
        //注册
        async doReg () {
            let data = this.regData;

            if (this.loading) {
                return;
            }

            this.checkData("reg", data);
            if (this.regData.allow) {
                let name = (this.regData.fullname || "").replace(
                    /(^\s*)|(\s*$)/g,
                    ""
                );
                let email = (this.regData.email || "").replace(
                    /(^\s*)|(\s*$)/g,
                    ""
                );
                let password = (this.regData.psw || "").replace(
                    /(^\s*)|(\s*$)/g,
                    ""
                );
                let resdata = {
                    email: email,
                    name: name,
                    password: Md5(password),
                    password_verify: Md5(password),
                };

                // 推广码
                try {
                    const config = JSON.parse(localStorage.getItem("CONFIG") || '{}');
                    const nowtime = new Date().getTime();
                    if (config.distributor && config.distributor.expire >= nowtime) {
                        resdata.identifier_code = config.distributor.code;
                    }
                } catch (err) {

                }

                this.loading = true;
                let res = await this.$http("postUserRegist", resdata);
                if (res.code == 0) {
                    this.$store.dispatch("setToken", res.data);
                    this.$uxMessage.success("Registration successful");
                    this.$gmeRepore('register');
                    this.loading = false;

                    // 清除推广码
                    try {
                        const config = JSON.parse(localStorage.getItem("CONFIG") || '{}');
                        delete config.distributor;
                        localStorage.setItem("CONFIG", JSON.stringify(config));
                    } catch (err) {

                    }
                } else if (res.code == 31) {
                    this.regTip.email = res.msg;
                    this.$uxMessage.warning(res.msg);
                    this.loading = false;
                } else {
                    this.$uxMessage.warning(res.msg);
                    this.loading = false;
                }
            }
        },
        //验证
        checkData (name, data, type) {
            let b = true;
            if (name == "reg") {
                if (!type) {
                    if (data.email != "") {
                        if (RE.email.test(data.email)) {
                            this.$set(this.regTip, "email", "");
                        } else {
                            b = false;
                            this.$set(
                                this.regTip,
                                "email",
                                "Please enter a valid format"
                            );
                        }
                    } else {
                        b = false;
                        this.$set(
                            this.regTip,
                            "email",
                            "Please enter a valid email address"
                        );
                    }
                    if (data.psw != "") {
                        if (RE.psw.test(data.psw)) {
                            this.$set(this.regTip, "psw", "");
                        } else {
                            b = false;
                            this.$set(
                                this.regTip,
                                "psw",
                                "The password must be at least 6 characters"
                            );
                        }
                    } else {
                        b = false;
                        this.$set(
                            this.regTip,
                            "psw",
                            "please enter the correct password"
                        );
                    }
                    if (data.fullname == "") {
                        b = false;
                        this.$set(
                            this.regTip,
                            "fullname",
                            "Please enter your full name"
                        );
                    } else {
                        this.$set(this.regTip, "fullname", "");
                    }
                } else {
                    if (type == "email") {
                        if (data.email != "") {
                            if (RE.email.test(data.email)) {
                                this.$set(this.regTip, "email", "");
                            } else {
                                b = false;
                                this.$set(
                                    this.regTip,
                                    "email",
                                    "Please enter a valid format"
                                );
                            }
                        } else {
                            b = false;
                            this.$set(
                                this.regTip,
                                "email",
                                "Please enter a valid email address"
                            );
                        }
                    }
                    if (type == "psw") {
                        if (data.psw != "") {
                            if (RE.psw.test(data.psw)) {
                                this.$set(this.regTip, "psw", "");
                            } else {
                                b = false;
                                this.$set(
                                    this.regTip,
                                    "psw",
                                    "The password must be at least 6 characters"
                                );
                            }
                        } else {
                            b = false;
                            this.$set(
                                this.regTip,
                                "psw",
                                "please enter the correct password"
                            );
                        }
                    }
                    if (type == "fullname") {
                        if (data.fullname == "") {
                            b = false;
                            this.$set(
                                this.regTip,
                                "fullname",
                                "Please enter your full name"
                            );
                        } else {
                            this.$set(this.regTip, "fullname", "");
                        }
                    }
                }
                this.regData.allow = b;
            } else {
                if (!type) {
                    if (data.email != "") {
                        if (RE.email.test(data.email)) {
                            this.$set(this.loginTip, "email", "");
                        } else {
                            b = false;
                            this.$set(
                                this.loginTip,
                                "email",
                                "Please enter a valid format"
                            );
                        }
                    } else {
                        b = false;
                        this.$set(
                            this.loginTip,
                            "email",
                            "Please enter a valid email address"
                        );
                    }
                    if (data.psw == "") {
                        b = false;
                        this.$set(
                            this.loginTip,
                            "psw",
                            "please enter the correct password"
                        );
                    } else {
                        this.$set(this.loginTip, "psw", "");
                    }
                } else {
                    if (type == "email") {
                        if (data.email != "") {
                            if (RE.email.test(data.email)) {
                                this.$set(this.loginTip, "email", "");
                            } else {
                                b = false;
                                this.$set(
                                    this.loginTip,
                                    "email",
                                    "Please enter a valid format"
                                );
                            }
                        } else {
                            b = false;
                            this.$set(
                                this.loginTip,
                                "email",
                                "Please enter a valid email address"
                            );
                        }
                    }
                    if (type == "psw") {
                        if (data.psw == "") {
                            b = false;
                            this.$set(
                                this.loginTip,
                                "psw",
                                "please enter the correct password"
                            );
                        } else {
                            if (RE.psw.test(data.psw)) {
                                this.$set(this.loginTip, "psw", "");
                            } else {
                                b = false;
                                this.$set(
                                    this.loginTip,
                                    "psw",
                                    "The password must be at least 6 characters"
                                );
                            }
                        }
                    }
                }

                this.loginData.allow = b;
            }
        },
        //注册登录忘记密码 | 1、2、3
        toStatus (n) {
            if (n == 1) {
                for (let i in this.regTip) {
                    this.regTip[i] = "";
                }
                for (let i in this.regData) {
                    this.regData[i] = "";
                }
                this.regData.allow = true;
            }
            if (n == 2) {
                for (let i in this.loginTip) {
                    this.loginTip[i] = "";
                }
                for (let i in this.loginData) {
                    this.loginData[i] = "";
                }
                this.loginData.allow = true;
            }
            if (n == 3) {
                this.forgetShow = "";
                this.fStatus = 1;
                this.forgetEmail = "";
            }
            if (n != 3) {
            }
            this.status = n;
        },
        //忘记密码 | 1、2
        toFstatus (n) {
            this.fStatus = n;
        },
        //忘记密码请求
        async doForgetPass () {
            this.forgetShow = "";
            if (!RE.email.test(this.forgetEmail)) {
                this.forgetShow = "1";
                return;
            }
            let email = (this.forgetEmail || "").replace(/(^\s*)|(\s*$)/g, "");
            let res = await this.$http("postForgetPass", { email: email });
            if (res.code == 0) {
                this.toFstatus(2);
                return;
            }
            if (res.code == 6004) {
                this.forgetShow = "2";
            }
            this.$uxMessage.warning(res.msg);
        },
        initData () {
            Object.assign(this.$data, this.$options.data());
        },

        // 检查用户是否可用，未过期
        async loginAvailable () {
            let token = this.$store.getters["getToken"];
            let available = false;
            if (token) {
                await this.$store.dispatch("user/updateUserInfo", { source: 'login' })
                if (this.userInfo && (this.userInfo.contact_email || this.userInfo.email)) {
                    available = true;
                } else {
                    available = false;
                }

            } else {
                // 没有token 肯定 过期
                available = false;
            }

            // 如果已经过期，则清空token
            if (!available) {
                // console.log(2222222);
                // this.$store.dispatch("removeToken");
                // this.$store.dispatch("user/removeUserInfo");
            }
            return available;
        },
        async open () {
            let available = await this.loginAvailable();
            if (available) {
                //已经登录状态下执行回调
                this.loginCallBack();
                return true;
            } else {
                this.show = true;
                return false;
            }
        },

        close () {
            if (!this.checkForceLogin(true)) {
                this.show = false;
                //重置回调
                this.callBackArray = [];
                this.$emit("close");
            }
        },
        //执行回调
        loginCallBack () {
            this.callBackArray.map((item) => {
                if (typeof item == "function") {
                    item();
                }
            });
        },
        //添加回调函数
        callBackPush (callback) {
            //判断是否为数组，如果不是则push。
            if (Array.isArray(callback)) {
                this.callBackArray.push(...callback);
            } else {
                this.callBackArray.push(callback);
            }
        },

        userLogin (callback) {
            this.toStatus(2);
            this.open();
            if (callback) {
                this.callBackPush(callback);
            }
        },
        userSignup (callback) {

            this.open();
            this.toStatus(1);
            if (callback) {
                this.callBackPush(callback);
            }
        },
        //退出登录
        // userLogout (callback) {

        //     // 触发全局的退出事件
        //     this.$emit("global:beforeLogout").then(res => {

        //         this.$store.dispatch("removeToken");
        //         this.$store.dispatch("user/removeUserInfo");
        //         //数据初始化
        //         this.initData();
        //         if (callback) {
        //             this.callBackPush(callback);
        //         }

        //         this.$emit("global:afterLogout")
        //     }).catch(error => {
        //         // 异常的，不管
        //         // console.log('err', error)
        //     })

        // },
        // 检查强制登录
        checkForceLogin (check) {
            let path = this.$route.path;
            let isUser = /^\/(settings|billing|user|order|branding|synchronize|distributor)(\/\S*)?$/.test(path);
            let popup = !this.isLogin && isUser;
            if (popup && !this.show) {
                this.toStatus(2);
                this.open();
            }
        },
    },
    created () {
        if (process.client) {
            this.checkForceLogin();
            this.$on("global:userLogin", this.userLogin);
            // this.$on("global:userLogout", this.userLogout);
            this.$on("global:userSignup", this.userSignup);

            // 如果有推广码
            try {
                const query = this.$route.query || {}
                const config = JSON.parse(localStorage.getItem("CONFIG") || '{}');
                const nowtime = new Date().getTime();
                if (query.code) {
                    // 有推广码，则存入
                    const validity = 30 * 24 * 60 * 60 * 1000; // 有效期30天
                    config.distributor = { code: query.code, expire: nowtime + validity }
                    localStorage.setItem("CONFIG", JSON.stringify(config));
                } else if (config.distributor && config.distributor.expire < nowtime) {
                    // 本地已经有推广码了，判断过期时间
                    // 过期了
                    delete config.distributor;
                    localStorage.setItem("CONFIG", JSON.stringify(config));
                }
            } catch (e) {
                // 错误
                console.log(e)
            }

        }
    },
    mounted () { },
    beforeDestroy () { },
    destroyed () { },
};
</script>

<style lang="scss" scoped>
.login {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    opacity: 0;
    z-index: 99;
    pointer-events: none;
    transition: opacity 0.5s;
    &.active {
        opacity: 1;
        pointer-events: all;
    }
}

.login-dialog {
    width: 100vw;
    height: 100vh;
    max-width: 900px;
    max-height: 666px;
    background: #ffffff;
    border-radius: 10px;
    overflow: hidden;
}

.login-close {
    position: absolute;
    right: 14px;
    top: 12px;
    text-align: center;
    font-size: 18px;
    border: none;
    background: none;
    padding: 0;
    margin: 0;
    cursor: pointer;
    z-index: 1;
}

.login-dialog {
    & > div {
        h2 {
            align-self: flex-start;
            font-size: 24px;

            font-weight: 600;
            color: #000000;
            margin: 0 0 22px 0;
            user-select: none;
        }
        .google-btn {
            cursor: pointer;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 42px;
            background: #ffffff;
            border-radius: 4px;
            font-size: 14px;
            .svg-google {
                width: 24px;
                height: 24px;
                margin: 0 12px 0 0;
            }
        }
        .division {
            font-size: 14px;
            color: #000;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            position: relative;
            margin: 16px 0;
        }
        .other-link {
            align-self: flex-start;
            font-size: 14px;
            color: #555;
            a {
                color: #555555;
                text-decoration: underline;
                &:hover {
                    color: #ea4c89;
                }
            }
        }
        > div {
            width: 360px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin: 0 auto;
        }
    }
}

.diabody-reg {
    padding-left: 460px;
    padding-right: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    &::before {
        content: '';
        position: absolute;
        height: 100%;
        width: 380px;
        left: 0;
        top: 0;
        background-color: #fafafa;
        background-repeat: no-repeat;
        background-size: 188px, 372px;
        background-image: url('https://img.podpartner.com/static/images-20230202/register-aside.png');
        background-position: center;
        border-radius: 10px 0 0 10px;
    }
}

.diabody-login {
    padding-right: 460px;
    padding-left: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    position: relative;

    &::before {
        content: '';
        position: absolute;
        height: 100%;
        width: 380px;
        right: 0;
        top: 0;
        background-color: #fafafa;
        background-repeat: no-repeat;
        background-size: 380px, 236px;
        background-image: url('https://img.podpartner.com/static/images-20230202/login-aside.png');
        background-position: center;
        border-radius: 0 10px 10px 0;
    }
}

.diabody-forget {
    padding-right: 460px;
    padding-left: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    > h2 {
        margin-bottom: 72px !important;
    }
    > h4 {
        font-size: 16px;

        color: #000000;
        line-height: 22px;
        font-weight: 400;
        margin-bottom: 24px;
    }
    > button {
        width: 100%;
        margin-bottom: 170px;
    }
    > button + p {
        align-self: flex-start;
        font-size: 14px;

        color: #555555;
        line-height: 16px;
        a {
            color: #ea4c89;
            text-decoration: none;
            &:hover {
                color: #d5417a;
            }
        }
    }
    &::before {
        content: '';
        position: absolute;
        height: 100%;
        width: 380px;
        right: 0;
        top: 0;
        background-color: #fafafa;
        background-repeat: no-repeat;
        background-size: 197px, 136px;
        background-image: url('https://img.podpartner.com/static/images-20230202/forget-eamil.png');
        background-position: center;
        border-radius: 0 10px 10px 0;
    }
}

.login_form {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin-bottom: 10px;
    > label {
        position: relative;
        height: 64px;
        > input {
            vertical-align: top;
        }
        > em {
            font-size: 12px;

            color: #f44336;
            line-height: 16px;
            position: absolute;
            bottom: 4px;
            left: 0;
            a {
                font-size: 14px;
                color: #555555;
                text-decoration: underline;
                &:hover {
                    color: #ea4c89;
                }
            }
        }
        > i {
            line-height: 20px;
            font-size: 20px;
            cursor: pointer;
            position: absolute;
            top: 10px;
            right: 14px;
        }
    }
    .submit {
        width: 100%;
        padding: 12px 0;
        font-size: 14px;
        text-align: center;
    }
}

a {
    cursor: pointer;
}

.visibility-hid {
    visibility: hidden !important;
}

.error-border {
    ::v-deep .el-input__inner {
        border-color: #f6b2cd;
    }
}

button[type='text'] {
    align-self: flex-start;
    white-space: nowrap;
    border: none;
    padding: 0;
    color: #ea4c89;
    &:hover {
        color: #d5417a;
        text-decoration: underline;
    }
}

@media (max-width: 960px) {
    .diabody-login,
    .diabody-reg,
    .diabody-forget {
        padding: 52px 14px 0;
        justify-content: flex-start;
        box-sizing: border-box;
        &::before {
            display: none;
        }

        & > h2 {
            width: 100%;
            text-align: center;
        }

        input,
        button {
            min-height: 40px;
        }

        button[type='text'] {
            font-weight: bold;
        }
    }

    .diabody-forget {
        & > button {
            margin-bottom: 60px;
        }

        & > button + p a {
            font-weight: bold;
        }
    }
}
</style>
